﻿/*Description:二维码转换
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:Wangjh 
'create Date:20211028
'Rewriter:
'Rewrite Date:
 * */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QRCoder;
using System.Drawing;
using System.IO;
using System.Text;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using DatabaseAccess.DBUtility;
using System.Xml;
using System.Data;

public partial class containerQrCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        

    }

    protected void btn_Click(object sender, EventArgs e)
    {
        var mDT = getContainerData(txtInput.Text);
        result.Text = "";
        var InnerHtml = string.Empty;
        var index = 0;
        if (mDT.Rows.Count > 0)
        {
            for (var j = 0; j < mDT.Rows.Count;j++ )
            {
                DataRow row = mDT.Rows[j];
                var ddt = getStepCheckPoint(row["containerName"].ToString(),null);
                //DataTable sdt = getStepCheckPoint(row["containerName"].ToString(), "1");
                if (ddt.Rows.Count > 0)
                {
                        var contentData = string.Empty;
                        var container = row["productname"].ToString() + "/{0}" + "#" + ddt.Rows.Count + "|" + row["realcontainerno"].ToString();
                        var xml2 = getXml(contentData.TrimEnd(','), container);
                        byte[] a = Encoding.Default.GetBytes(xml2);
                        contentData = getcontentData(ddt, a.Length);//最大长度--sdata--
                        for (var i = 0; i < contentData.Split(';').Length; i++)
                        {
                            index++;
                            var content=contentData.Split(';')[i].ToString();
                            if (!string.IsNullOrWhiteSpace(contentData))
                            {
                                var xml = getXml(content, string.Format(container, contentData.Split(';').Length));
                                var json = getJson(content, string.Format(container, contentData.Split(';').Length));
                                var ImageUrl = string.Format("data:image/Jpeg;base64,{0}", CreateQRCodeImg(json));
                                var containerBM = contentData.Split(';').Length > 1 ? "(" + (i+1) + ")" : "";
                                var Class = ("Imgdiv_"+index) +" "+ (j == 0 && i == 0 ? "showImg" : "hiddenImg");
                                InnerHtml += "<div class=' "+ Class + "'><p>" + row["containerName"].ToString() + containerBM + "</p>";
                                InnerHtml += "<image  src=" + ImageUrl + " style='height:100%;width:250px;'/></div>";
                            }
                        }
                    
                }
                else
                {
                    result.Text = "查询批次号没有维护检测项信息";
                }
            }
            ImageList.InnerHtml =InnerHtml;
            Total.Value = index.ToString();
        }
        else
        {
            result.Text = "查询不到对应批次号信息，请输入正确批次号再进行操作";
        }
    }

    private string getcontentData(DataTable ddt, int headLength) 
    {
        var contentData = string.Empty;
        var specno = ddt.Rows[0]["specno"].ToString();
        var con = specno + "$"; //string.Empty;
        for (var i = 0; i < ddt.Rows.Count; i++)
        {
            if (!specno.Equals(ddt.Rows[i]["specno"].ToString())) {
                specno = ddt.Rows[i]["specno"].ToString();
                con += specno + "$";
            }
                byte[] b = Encoding.Default.GetBytes(con);
                if ((b.Length + headLength) < 550)//2953
                {
                    con += ddt.Rows[i]["sdata"] + ",";
                }
                else{
                    contentData += con.TrimEnd(',') + ";";
                    //con = specno + "$"; //string.Empty;
                    con += ddt.Rows[i]["sdata"] + ",";
                }
        }
        //if (!string.IsNullOrWhiteSpace(con)) { contentData += con.TrimEnd(',') + ";"; }
        if (!specno.Equals(con.Replace("$",""))) { contentData += con.TrimEnd(',') + ";"; }
        return contentData.TrimEnd(';');
    }

    private DataTable getContainerData(string containerName)
    {
        var sqlStr = @"SELECT con.containername,con.realcontainerno,con.productname 
                    FROM containercurrentinfo con WHERE containername in('{0}')";
        return DatabaseHelper.Query_ReturnDatTable(string.Format(sqlStr, containerName.Replace(",","','")));
    }

    private DataTable getStepCheckPoint(string containerName,string type)
    {
        var sqlStr = @"SELECT con.containername,con.realcontainerno,con.productname,con.productrevision,con.workflowname,con.workflowrevision,s.specno,
ws.workflowstepid,ws.workflowstepname,st.checkno,
st.bubblenumber,st.floorfloat,st.basevalue,st.ceilfloat,
st.bubblenumber||'/'||st.SINGLESIGN||'#'||st.floorfloat||'|'||st.basevalue||'|'||st.ceilfloat sdata
FROM containercurrentinfo con 
LEFT JOIN workflowstep ws ON ws.workflowid=DECODE(con.isinstore,1,con.bsworkflowid,con.workflowid)
LEFT JOIN specbase sp ON sp.specbaseid=ws.specbaseid
LEFT JOIN spec s ON s.specbaseid=sp.specbaseid OR s.specid=ws.specid
LEFT JOIN stepcheckpoint st ON st.workflowstepid=ws.workflowstepid
WHERE st.stepcheckpointid IS NOT NULL AND con.containername IN('{0}')
ORDER BY s.specno,st.checkno,st.bubblenumber";
        if(!string.IsNullOrWhiteSpace(type)){
            sqlStr = "SELECT SPECNO,containername FROM (" + sqlStr + ") GROUP BY SPECNO,containername";
        }
        return DatabaseHelper.Query_ReturnDatTable(string.Format(sqlStr, containerName.Replace(",","','")));
    }
    private string getXml(string contentData, string containername)
    {
        XmlDocument doc = new XmlDocument();
        doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
        XmlNode checklist = doc.CreateElement("checklist");
        XmlNode container = doc.CreateElement("container");
        container.InnerText = containername;
        checklist.AppendChild(container);
        XmlNode content = doc.CreateElement("content");
        content.InnerText = contentData;
        checklist.AppendChild(content);
        doc.AppendChild(checklist);
        return doc.InnerXml;
    }
    protected string CreateQRCodeImg(string str)
    {
        QRCoder.QRCodeGenerator qrGenerator = new QRCodeGenerator();
        
        QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCodeGenerator.ECCLevel.L);
        QRCode qrcode = new QRCode(qrCodeData);

        Bitmap qrCodeImage = qrcode.GetGraphic(6, Color.Black, Color.White, null, 5, 1, false);
        MemoryStream ms = new MemoryStream();
        qrCodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        return Convert.ToBase64String(ms.ToArray());
    }

    private string getJson(string contentData, string containername)
    {
        Dictionary<string, object> dic = new Dictionary<string, object>();
        dic.Add("container", containername);
        dic.Add("content", contentData);
        //Dictionary<string, object> p = new Dictionary<string, object>();
        //p.Add("checklist",dic);
        return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
    }
}